package com.centaline.androidsalesblog.activities;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.os.Bundle;
import android.text.TextUtils;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.centaline.androidsalesblog.R;
import com.centaline.androidsalesblog.base.BaseActivity;
import com.centaline.androidsalesblog.constants.CommonConstant;
import com.centaline.androidsalesblog.constants.ExtraConstant;
import com.centaline.androidsalesblog.model.businissobject.ShareBo;
import com.centaline.androidsalesblog.utils.AccessTokenKeeper;
import com.centaline.androidsalesblog.utils.WeiXinUtil;
import com.sina.weibo.sdk.api.ImageObject;
import com.sina.weibo.sdk.api.TextObject;
import com.sina.weibo.sdk.api.WebpageObject;
import com.sina.weibo.sdk.api.WeiboMultiMessage;
import com.sina.weibo.sdk.api.share.BaseResponse;
import com.sina.weibo.sdk.api.share.IWeiboHandler;
import com.sina.weibo.sdk.api.share.IWeiboShareAPI;
import com.sina.weibo.sdk.api.share.SendMultiMessageToWeiboRequest;
import com.sina.weibo.sdk.api.share.WeiboShareSDK;
import com.sina.weibo.sdk.auth.AuthInfo;
import com.sina.weibo.sdk.auth.Oauth2AccessToken;
import com.sina.weibo.sdk.auth.WeiboAuthListener;
import com.sina.weibo.sdk.auth.sso.SsoHandler;
import com.sina.weibo.sdk.constant.WBConstants;
import com.sina.weibo.sdk.exception.WeiboException;
import com.sina.weibo.sdk.utils.Utility;
import com.tencent.mm.sdk.modelmsg.SendMessageToWX;
import com.tencent.mm.sdk.modelmsg.WXMediaMessage;
import com.tencent.mm.sdk.modelmsg.WXWebpageObject;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import java.util.Locale;

/**
 * sina分享页面
 * Created by guilin on 16/5/9.
 */
public class ShareActivity extends BaseActivity implements IWeiboHandler.Response {

    private int shareType;
    private ShareBo shareBo;

    private IWXAPI iwxapi;
    private AuthInfo authInfo;
    private SsoHandler ssoHandler;
    private IWeiboShareAPI iWeiboShareAPI;
    private Oauth2AccessToken accessToken;
    private WeiboAuthListener weiboAuthListener = new WeiboAuthListener() {
        @Override
        public void onComplete(Bundle bundle) {
            accessToken = Oauth2AccessToken.parseAccessToken(bundle);
            if (accessToken.isSessionValid()) {
                loadImage();
            } else {
                authError();
            }
        }

        @Override
        public void onWeiboException(WeiboException e) {
            AccessTokenKeeper.clear(ShareActivity.this);
            authError();
        }

        @Override
        public void onCancel() {
            userCancel();
        }
    };

    @Override
    protected int setLayoutId() {
        return R.layout.activity_share;
    }

    @Override
    protected void findViews() {
        setUniversalToolbar();
    }

    @Override
    protected void initViews() {
        shareBo = getIntent().getParcelableExtra(ExtraConstant.ShareContent);
        shareType = getIntent().getIntExtra(ExtraConstant.ShareType, 1);
        switch (shareType) {
            case 0:
                setToolbarTitle("分享到微博");
                authInfo = new AuthInfo(this, CommonConstant.APP_KEY_SINA,
                        CommonConstant.REDIRECT_URL,
                        CommonConstant.SCOPE_SIAN);
                iWeiboShareAPI = WeiboShareSDK.createWeiboAPI(this,
                        CommonConstant.APP_KEY_SINA);
                iWeiboShareAPI.registerApp();
                ssoHandler = new SsoHandler(this, authInfo);
                ssoHandler.authorize(weiboAuthListener);
                break;
            case 1:
                setToolbarTitle("分享到微信");
                iwxapi = WXAPIFactory.createWXAPI(this, CommonConstant.APP_ID_WX);
                if (!iwxapi.isWXAppInstalled()) {
                    toast("微信未安装");
                    finish();
                }
                iwxapi.registerApp(CommonConstant.APP_ID_WX);
                loadImage();
                break;
            case 2:
                setToolbarTitle("分享到朋友圈");
                iwxapi = WXAPIFactory.createWXAPI(this, CommonConstant.APP_ID_WX);
                if (!iwxapi.isWXAppInstalled()) {
                    toast("微信未安装");
                    finish();
                }
                iwxapi.registerApp(CommonConstant.APP_ID_WX);
                loadImage();
                break;
            default:
                break;
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        if (savedInstanceState != null) {
//            iWeiboShareAPI.handleWeiboResponse(getIntent(), this);
//        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        iWeiboShareAPI.handleWeiboResponse(intent, this);
    }

    private void loadImage() {
        if (TextUtils.isEmpty(shareBo.getImageUrl())) {
            Glide.with(this)
                    .load(R.drawable.ic_centa_square_logo)
                    .override(150, 150)
                    .centerCrop()
                    .into(new SimpleTarget<GlideDrawable>() {
                        @Override
                        public void onResourceReady(GlideDrawable resource, GlideAnimation<? super GlideDrawable> glideAnimation) {
                            Bitmap bitmap = Bitmap.createBitmap(resource.getIntrinsicWidth(),
                                    resource.getMinimumHeight(), Bitmap.Config.RGB_565);
                            Canvas canvas = new Canvas(bitmap);
                            resource.setBounds(0, 0, resource.getIntrinsicWidth(), resource.getIntrinsicHeight());
                            resource.draw(canvas);
                            switch (shareType) {
                                case 0:
                                    weibo(bitmap);
                                    break;
                                case 1:
                                    weixin(bitmap, false);
                                    break;
                                case 2:
                                    weixin(bitmap, true);
                                    break;
                                default:
                                    break;
                            }
                        }
                    });
        } else {
            Glide.with(this)
                    .load(shareBo.getImageUrl())
                    .override(150, 150)
                    .error(R.drawable.ic_centa_square_logo)
                    .centerCrop()
                    .into(new SimpleTarget<GlideDrawable>() {
                        @Override
                        public void onResourceReady(GlideDrawable resource, GlideAnimation<? super GlideDrawable> glideAnimation) {
                            Bitmap bitmap = Bitmap.createBitmap(resource.getIntrinsicWidth(),
                                    resource.getMinimumHeight(), Bitmap.Config.RGB_565);
                            Canvas canvas = new Canvas(bitmap);
                            resource.setBounds(0, 0, resource.getIntrinsicWidth(), resource.getIntrinsicHeight());
                            resource.draw(canvas);
                            switch (shareType) {
                                case 0:
                                    weibo(bitmap);
                                    break;
                                case 1:
                                    weixin(bitmap, false);
                                    break;
                                case 2:
                                    weixin(bitmap, true);
                                    break;
                                default:
                                    break;
                            }
                        }
                    });
        }
    }

    private void weibo(Bitmap bitmap) {
        WeiboMultiMessage weiboMessage = new WeiboMultiMessage();
        TextObject textObject = new TextObject();
        ImageObject imageObject = new ImageObject();
        WebpageObject mediaObject = new WebpageObject();
        switch (shareBo.getComeFrom()) {
            case 0://二手房
            case 1:
                textObject.text =
                        String.format(Locale.CHINA, "大家帮忙参谋一下这套房源：%s、%s、%s、%s,%s",
                                shareBo.getHouseName(),
                                shareBo.getHouseType(),
                                shareBo.getArea(),
                                shareBo.getTotalPrice(),
                                shareBo.getApkUrl());


                imageObject.setImageObject(bitmap);

                mediaObject.identify = Utility.generateGUID();
                mediaObject.title = "或点此链接查看房源";
                mediaObject.description = "房源详情";
                mediaObject.setThumbImage(bitmap);
                mediaObject.actionUrl = shareBo.getHouseUrl();
                mediaObject.defaultText = "webPage";

                weiboMessage.textObject = textObject;
                weiboMessage.imageObject = imageObject;
                weiboMessage.mediaObject = mediaObject;
                break;
            case 2://小区
                textObject.text =
                        String.format(Locale.CHINA, "优质小区推荐：%s、%s、%s,%s",
                                shareBo.getHouseName(),
                                shareBo.getRegionGscop(),
                                shareBo.getAvgPrice(),
                                shareBo.getApkUrl());

                imageObject.setImageObject(bitmap);

                mediaObject.identify = Utility.generateGUID();
                mediaObject.title = "或点此链接查看房源";
                mediaObject.description = "房源详情";
                mediaObject.setThumbImage(bitmap);
                mediaObject.actionUrl = shareBo.getHouseUrl();
                mediaObject.defaultText = "webPage";

                weiboMessage.textObject = textObject;
                weiboMessage.imageObject = imageObject;
                weiboMessage.mediaObject = mediaObject;
                break;
            case 3://新房
                textObject.text =
                        String.format(Locale.CHINA, "优质楼盘推荐：%s、%s、%s,%s",
                                shareBo.getHouseName(),
                                shareBo.getRegionGscop(),
                                shareBo.getAvgPrice(),
                                shareBo.getApkUrl());

                imageObject.setImageObject(bitmap);

                mediaObject.identify = Utility.generateGUID();
                mediaObject.title = "或点此链接查看房源";
                mediaObject.description = "房源详情";
                mediaObject.setThumbImage(bitmap);
                mediaObject.actionUrl = shareBo.getHouseUrl();
                mediaObject.defaultText = "webPage";

                weiboMessage.textObject = textObject;
                weiboMessage.imageObject = imageObject;
                weiboMessage.mediaObject = mediaObject;
                break;
            case 4://经纪人店铺
                textObject.text =
                        String.format(Locale.CHINA, "%s,%s",
                                shareBo.getHouseDecription(),
                                shareBo.getApkUrl());

                imageObject.setImageObject(bitmap);

                mediaObject.identify = Utility.generateGUID();
                mediaObject.title = "或点此链接查看店铺";
                mediaObject.description = "店铺";
                mediaObject.setThumbImage(bitmap);
                mediaObject.actionUrl = shareBo.getHouseUrl();
                mediaObject.defaultText = "webPage";

                weiboMessage.textObject = textObject;
                weiboMessage.imageObject = imageObject;
                weiboMessage.mediaObject = mediaObject;
                break;
            default:
                break;
        }

        SendMultiMessageToWeiboRequest request = new SendMultiMessageToWeiboRequest();
        request.transaction = String.valueOf(System.currentTimeMillis());
        request.multiMessage = weiboMessage;
        iWeiboShareAPI.sendRequest(this, request, authInfo, accessToken.getToken(),
                new WeiboAuthListener() {
                    @Override
                    public void onComplete(Bundle bundle) {
                        Oauth2AccessToken newToken = Oauth2AccessToken
                                .parseAccessToken(bundle);
                        AccessTokenKeeper.writeAccessToken(ShareActivity.this,
                                newToken);
                    }

                    @Override
                    public void onWeiboException(WeiboException e) {
                        AccessTokenKeeper.clear(ShareActivity.this);
                        authError();
                    }

                    @Override
                    public void onCancel() {
                        userCancel();
                    }
                });
    }

    /**
     * 微信
     */
    private void weixin(Bitmap bitmap, boolean isScene) {
        iwxapi = WXAPIFactory.createWXAPI(this, CommonConstant.APP_ID_WX);
        WXWebpageObject webpage = new WXWebpageObject();
        WXMediaMessage msg = new WXMediaMessage(webpage);
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        switch (shareBo.getComeFrom()) {
            case 0://租售
            case 1:
                webpage.webpageUrl = shareBo.getHouseUrl();

                msg.title = String.format(Locale.CHINA, "%s %s %s %s",
                        shareBo.getHouseName(),
                        shareBo.getHouseType(),
                        shareBo.getArea(),
                        shareBo.getTotalPrice());
                msg.description = shareBo.getHouseDecription();
                msg.thumbData = WeiXinUtil.bmpToByteArray(bitmap, true);
                req.message = msg;
                break;
            case 2://小区
                webpage.webpageUrl = shareBo.getHouseUrl();
                msg.title = String.format(Locale.CHINA, "%s %s %s",
                        shareBo.getHouseName(),
                        shareBo.getRegionGscop(),
                        shareBo.getAvgPrice());
                msg.description = shareBo.getHouseDecription();
                msg.thumbData = WeiXinUtil.bmpToByteArray(bitmap, true);
                req.message = msg;
                break;
            case 3://新房
                webpage.webpageUrl = shareBo.getHouseUrl();
                msg.title = isScene ? String.format(Locale.CHINA, "%s %s %s",
                        shareBo.getHouseName(),
                        shareBo.getRegionGscop(),
                        shareBo.getAvgPrice()) :
                        shareBo.getHouseName();
                msg.description = String.format(Locale.CHINA, "%s %s",
                        shareBo.getRegionGscop(),
                        shareBo.getAvgPrice());
                msg.thumbData = WeiXinUtil.bmpToByteArray(bitmap, true);
                req.message = msg;
                break;
            case 4://经纪人店铺
                webpage.webpageUrl = shareBo.getHouseUrl();
                msg.title = isScene ? shareBo.getHouseDecription() : shareBo.getHouseName();
                msg.description = shareBo.getHouseDecription();
                msg.thumbData = WeiXinUtil.bmpToByteArray(bitmap, true);
                req.message = msg;
                break;
            default:
                break;
        }
        req.scene = isScene ? SendMessageToWX.Req.WXSceneTimeline
                : SendMessageToWX.Req.WXSceneSession;
        req.transaction = String.format(Locale.CHINA, "webpage%d", System.currentTimeMillis());
        iwxapi.sendReq(req);
        finish();
    }

    private void success() {
        toast("分享成功");
        finish();
    }

    private void fail() {
        toast("分享失败，请重试");
        finish();
    }

    private void authError() {
        toast("授权出错");
        finish();
    }

    private void userCancel() {
        toast("取消分享");
        finish();
    }

    @Override
    public void onResponse(BaseResponse baseResponse) {
        switch (baseResponse.errCode) {
            case WBConstants.ErrorCode.ERR_OK:
                success();
                break;
            case WBConstants.ErrorCode.ERR_CANCEL:
                userCancel();
                break;
            default:
                fail();
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (ssoHandler != null) {
            ssoHandler.authorizeCallBack(requestCode, resultCode, data);
        }
    }
}
